import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { UserService } from 'src/app/service/user.service';
import { YearawardService } from '../../../yearaward.service';
import { BaseService } from 'src/app/service/base.service';
import { UtilsService } from 'src/app/service/utils.service';

@Component({
  selector: 'app-enter',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss', '../../../commonList.scss'],
})
export class EnterComponent implements OnInit, OnDestroy {
  @Input() timeConfig: any[] = [];
  /* ___ _ ___ */
  public deployUrl: string; /* 资源地址前缀 */
  /* ___ _ ___ */
  public isPC = false; /* 是否pc */
  public isAndroid = false; /* 是否安卓 */
  public onRefrash: any; /* 刷新中 */
  public pageSize = 48; /* 每页条数 */
  public stageId: number;//请求数据ID
  public haveOver: boolean = false;//是否已经结榜
  public nowDate: any;
  public reshing = null;
  /* ___ _ ___ */
  public top3List: EndYear.IAnchor[] = []; /* TOP3 */
  public othersList: EndYear.IAnchor[] = []; /* 危险区 */
  public safetyList: EndYear.IAnchor[] = []; /* 安全区 */
  public dangersList: EndYear.IAnchor[] = []; /* 淘汰区 */
  public dangerIndex = 0;
  public othersIndex = 0;
  public timeArr: any = [];
  public hoursRightNum: number = 0;
  public hoursLeftNum: number = 0;
  public fenRightNum: number = 0;
  public fenLeftNum: number = 0;
  public miaoRightNum: number = 0;
  public miaoLeftNum: number = 0;
  public timer: any = null;
  public currentAnchorInfo: EndYear.ICurrentAnchor = {
    nickname: '',
    avatarUrl: '',
    score: 0,
    rankDesc: '-',
    rank: 0,
    isMysteryMan: false,
  }; /* 当前主播信息 */

  constructor(
    private userService: UserService,
    private yearawardService: YearawardService,
    private baseService: BaseService,
    private utilsservice: UtilsService
  ) { }

  ngOnInit(): void {
    // 获取
    this.deployUrl = this.userService.getDeployUrl();
    this.isPC = this.userService.getIsPc();
    this.isAndroid = this.utilsservice.getBrowserVersion();
    this.initPage();
    // 组件刷新通信
    this.reshing = this.utilsservice.MsgSub.subscribe((res: any) => {
      this.initPage();
    });

  }
  ngOnDestroy() {
    clearTimeout(this.timer);
    this.timer = null;
    if (this.reshing) {
      this.reshing.unsubscribe();
    }
  }
  public initPage() {
    this.timeArr = this.timeConfig.filter(itm => itm.type === 7).sort(this.sortBy('startTime', undefined)); // 时间配置
    this.nowDate = new Date().getTime();
    // 活动未开始
    if (this.nowDate < this.timeArr[0].startTime * 1000) {
      return;
    }
    // 已结榜
    if (this.nowDate > this.timeArr[this.timeArr.length - 1].endTime * 1000) {
      this.stageId = this.timeArr[this.timeArr.length - 1].id;
      this.haveOver = true;
      this.getList();
      this.getCurrentAnchor();
    }
    if (this.nowDate > this.timeArr[0].startTime * 1000 && this.nowDate < this.timeArr[0].endTime * 1000) {
      this.stageId = this.timeArr[0].id;
      this.haveOver = false;
      // 请求数据
      this.getList();
      this.getCurrentAnchor();
      this.countTime(this.timeArr[0].endTime);
    }
  }
  // 排序方法 attr为排序key,rev false升序 true降序
  public sortBy(attr: any, rev: any) {
    if (rev === undefined) {
      rev = 1;
    } else {
      rev = (rev) ? 1 : -1;
    }

    return (a, b) => {
      a = a[attr];
      b = b[attr];
      if (a < b) {
        return rev * -1;
      }
      if (a > b) {
        return rev * 1;
      }
      return 0;
    };
  }
  // 获取榜单
  public getList() {
    return new Promise((r, j) => {
      this.onRefrash = true;
      this.yearawardService.getActivityRanking(
        (res) => {
          this.onRefrash = false;
          if (res.code === 200) {
            const len = 3 - res.data.list.length;
            if (len > 0) {
              for (let i = 0; i < len; i++) {
                res.data.list.push({
                  avatarUrl: '',
                  score: 0,
                  rank: i + 1,
                  nickname: '虚位以待',
                  rankDesc: '-',
                });
              }
            }
            this.top3List = res.data.list.slice(0, 3) || [];
            this.othersList = res.data.list.slice(3) || [];
            r(res.data);
          } else {
            this.baseService.showToast(res.message, 1500);
            j();
          }
        },
        this.stageId,
        this.pageSize,
        (err) => {
          this.onRefrash = false;
        }
      );
    });
  }

  /**
   * @description: 获取当前主播
   */
  getCurrentAnchor() {
    const ob = this.yearawardService.getCurrentAnchorRanking(
      (res: any) => {
        if (res.code === 200) {
          this.currentAnchorInfo = res.data;
        } else {
          this.baseService.showToast(res.message, 1500);
        }
      },
      this.baseService.getCurrentId(),
      this.stageId,
      (err: any) => {}
    );
  }
  // 跳转直播间
  public gotoRoom(item: any, type: any) {
    if ((type === 'anchor' && !item.uid) || (type === 'user' && !item.userUid)) {
      return;
    }
    const obj = { ...item };
    if (type === 'anchor') {
      obj.isMysteryMan = false;
    }
    obj.livImage = item.avatarUrl;
    this.utilsservice.gotoRoom(obj, type);
  }
  // 倒计时
  public countTime(time) {
    const date = new Date();
    const now = date.getTime();
    let differTime = null;
    differTime = time * 1000 - now;
    let h: number;
    let m: number;
    let s: number;
    if (differTime >= 0) {
      h = Math.floor((differTime / 1000 / 60 / 60));
      m = Math.floor((differTime / 1000 / 60) % 60);
      s = Math.floor((differTime / 1000) % 60);
      if (h < 10) {
        this.hoursLeftNum = 0;
        this.hoursRightNum = h;
      } else {
        this.hoursLeftNum = Math.floor(h / 10);
        this.hoursRightNum = h % 10;
      }
      if (m < 10) {
        this.fenLeftNum = 0;
        this.fenRightNum = m;
      } else {
        this.fenLeftNum = Math.floor(m / 10);
        this.fenRightNum = m % 10;
      }
      if (s < 10) {
        this.miaoLeftNum = 0;
        this.miaoRightNum = s;
      } else {
        this.miaoLeftNum = Math.floor(s / 10);
        this.miaoRightNum = s % 10;
      }
      // 递归调用函数所以是延时器不是定时器
      this.timer = setTimeout(() => {
        this.countTime(time);
      }, 1000);
    }else{
      clearTimeout(this.timer);
      setTimeout(() => {
        this.initPage();
      }, 1000);
    }
  }
}
